package com.tarena.lbs.user.service.impl;

import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.dao.repository.UserRepository;
import com.tarena.lbs.user.pojo.param.UserParam;
import com.tarena.lbs.user.pojo.po.UserPO;
import com.tarena.lbs.user.pojo.vo.UserVO;
import com.tarena.lbs.user.service.UserService;
import com.tarena.lbs.user.utils.RandomUserName;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 用户核心服务实现
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public void register(UserParam param) throws BusinessException {
        // 1. 校验手机号唯一性
        Asserts.isTrue(StringUtils.isBlank(param.getPhone()), new BusinessException("-2", "手机号不能为空"));
        Asserts.isTrue(StringUtils.isBlank(param.getPassword()), new BusinessException("-2", "密码不能为空"));

        Long count = userRepository.countUserByPhone(param.getPhone());
        Asserts.isTrue(count > 0, new BusinessException("-2", "手机号已被注册"));
        log.info("--------------{}",param.getProviderType());

        // 2. 封装用户数据
        UserPO userPO = new UserPO();
        BeanUtils.copyProperties(param, userPO);
        userPO.setStatus(0); // 0-未绑定标签
        userPO.setRegTime(new Date());
        // 生成随机昵称和用户名
        String randomName = RandomUserName.createRandomName();
        userPO.setNickName(randomName);
        userPO.setUserName(randomName);
        System.out.println("-----------------"+userPO.getProviderType());

        // 3. 保存用户
        userRepository.save(userPO);
    }

    @Override
    public UserVO getById(Long id) {
        log.info("通过id查询用户信息");
        UserPO po = userRepository.getById(id.intValue());
        if(po!=null){
            UserVO vo=new UserVO();
            BeanUtils.copyProperties(po,vo);
            return vo;
        }else{
            log.info("用户不存在");
            return null;
        }
    }

    @Override
    public List<UserPO> list(UserParam param) throws BusinessException {
        log.info("查询用户列表{}", param);
        List<UserPO> list = userRepository.listUser(param);
        return list;
    }

    @Override
    public void delete(Integer id) {
        userRepository.deleteById(id);
    }


}
